package com.myc.train.member.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.myc.train.common.req.MemberTicketReq;
import com.myc.train.common.resp.PageResp;
import com.myc.train.common.utils.SnowUtil;
import com.myc.train.member.domain.Ticket;
import com.myc.train.member.domain.TicketExample;
import com.myc.train.member.mapper.TicketMapper;
import com.myc.train.member.req.TicketQueryReq;
import com.myc.train.member.req.TicketSaveReq;
import com.myc.train.member.resp.TicketQueryResp;
import io.seata.core.context.RootContext;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class TicketService {

    private static final Logger LOG = LoggerFactory.getLogger(TicketService.class);
    @Resource
    private TicketMapper ticketMapper;

    public void save(MemberTicketReq req) throws Exception {
//        LOG.info("seata全局事务ID save: {}", RootContext.getXID());
        DateTime now = DateTime.now();
        Ticket ticket = BeanUtil.copyProperties(req, Ticket.class);
        ticket.setId(SnowUtil.getSnowflakeNextId());
        ticket.setCreateTime(now);
        ticket.setUpdateTime(now);
        ticketMapper.insert(ticket);
        // 模拟被调用方出现异常
        // if (1 == 1) {
        //     throw new Exception("测试异常11");
        // }
    }

    public PageResp<TicketQueryResp> queryList(TicketQueryReq req){
       //定义查询条件
        TicketExample ticketExample = new TicketExample();
        //根据id倒序排序
        ticketExample.setOrderByClause("id desc");
        //创建查询对象
        TicketExample.Criteria criteria = ticketExample.createCriteria();
        //不为空则对其新增查询条件
        if(ObjUtil.isNotNull(req.getMemberId())){
            criteria.andMemberIdEqualTo(req.getMemberId());
        }

        //新增分页信息
        PageHelper.startPage(req.getPage(),req.getSize());
        //根据条件查询结果
        List<Ticket> tickets = ticketMapper.selectByExample(ticketExample);
        //new一个PageInfo并将结果放进来
        PageInfo<Ticket> ticketPageInfo = new PageInfo<>(tickets);
        //类拷贝
        List<TicketQueryResp> queryResps = BeanUtil.copyToList(tickets, TicketQueryResp.class);
        //new一个PageResp
        PageResp<TicketQueryResp> resp= new PageResp<>();
        //放数据
        resp.setTotal(ticketPageInfo.getTotal());
        resp.setList(queryResps);


        return resp;
    }

    public void delete(Long id){
        ticketMapper.deleteByPrimaryKey(id);
    }


}
